package io.handlerstream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Test;

public class ObjectStreamDemo {
	
	@Test
	public void objectwrite() throws IOException {
		FileOutputStream fos = new FileOutputStream("person.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeInt(100);
		oos.writeBoolean(true);
		oos.writeUTF("hello");
		oos.writeDouble(3.14);
		oos.flush();
		oos.close();
		fos.close();
	}
	
	@Test
	public void objectread() throws IOException {
		FileInputStream fos = new FileInputStream("person.txt");
		ObjectInputStream oos = new ObjectInputStream(fos);
		
		// 一定要按照写的顺序读
		int readInt = oos.readInt();
		boolean readBoolean = oos.readBoolean();
		String readUTF = oos.readUTF();
		double readDouble = oos.readDouble();
		
		oos.close();
		fos.close();
		
		System.out.println(readInt);
		System.out.println(readBoolean);
		System.out.println(readUTF);
		System.out.println(readDouble);
	}

	@Test
	public void personwrite() throws IOException {
		FileOutputStream fos = new FileOutputStream("person.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		// NotSerializableException 没有序列化异常
		Person p = new Person("zs",20,9999.99);
		// 写自定义类型
		oos.writeObject(p);
		oos.flush();
		
		oos.close();
		fos.close();
	}
	
	@Test
	public void personread() throws IOException, ClassNotFoundException{
		FileInputStream fis = new FileInputStream("person.txt");
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		// 反序列化： 把对象的属性从外部介质按照顺序读回来的过程
		Object p = ois.readObject();
		
		ois.close();
		fis.close();
		
		System.out.println(p.toString());
	}

}
